package com.dgut.crm.system.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.dgut.crm.system.dao.DepartmentRepository;
import com.dgut.crm.system.dao.NumberRepository;
import com.dgut.crm.system.entity.Department;
import com.dgut.crm.system.entity.Number;
import com.dgut.crm.system.entity.dto.NumberQueryDTO;

@Service
@Transactional
public class NumberService implements INumberService{
	@Autowired
	private NumberRepository numberRepository;
	@Autowired
	private DepartmentRepository departmentRepository;

	public void saveOrUpdate(NumberQueryDTO dto) {
		Number number = new Number();
		
		NumberQueryDTO.dtoToEntity(dto, number);
		number.setPassword("123456");
		//Department department= departmentRepository.findOne(dto.getDepartmentId());
		Department department= departmentRepository.findByName(dto.getDepartmentName());
		number.setDepartment(department);
		
		numberRepository.save(number);
	}
	public void delete(NumberQueryDTO dto) {
		Number number = new Number();
		NumberQueryDTO.dtoToEntity(dto, number);
		numberRepository.delete(number);
	}

	@Transactional(readOnly = true)
	public NumberQueryDTO findOne(Long id) {
		Number number = numberRepository.findOne(id);
		NumberQueryDTO dto = new NumberQueryDTO();
		NumberQueryDTO.entityToDto(dto, number);
		return dto;
	}

	@Override
	public void deleteNumbers(List<Long> ids) {
		// TODO Auto-generated method stub
		List<Number> numbers = (List<Number>) numberRepository.findAll(ids);
		if(numbers != null) {
			for (Number number : numbers) {
				number.setDepartment(null);
			}
			numberRepository.delete(numbers);
		}
	}
	
	@Transactional(readOnly = true)
	public Page<NumberQueryDTO> findAll(Specification<Number> spec, Pageable pageable) {
		Page<Number> list = numberRepository.findAll(spec, pageable);
		List<NumberQueryDTO> dtoLists = new ArrayList<NumberQueryDTO>();
		for (Number entity : list.getContent()) {
			NumberQueryDTO dto = new NumberQueryDTO();
			NumberQueryDTO.entityToDto(dto,entity);
			dtoLists.add(dto);
		}
		return new PageImpl<NumberQueryDTO>(dtoLists, pageable, list.getTotalElements());
	}
	@Override
	public void findByNameAndPassword() {
		// TODO Auto-generated method stub
		
	}
	
}
